package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import cn.com.elite.Util;
import cn.com.kh.UcisXML;
import java.net.URLEncoder;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

/**
 *
 * @Title: OBsendtask
 * @Description:外呼催缴任务待发送接口--内部
 * @author: cosson
 * @date 2021-03
 *
 */


public class OBsendToIVR implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(OBsendToIVR.class);
		private String charset = "utf-8";
		private int timeout = 100000;
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		int minute = cal.get(Calendar.MINUTE);
		int secound = cal.get(Calendar.SECOND);
		
		java.sql.Time d1  = new java.sql.Time(9, 0, 0);
		java.sql.Time d2  = new java.sql.Time(hour, minute, secound);
		java.sql.Time d3  = new java.sql.Time(20, 0, 0);
		
		int timei = d2.compareTo(d1);
		int timej = d3.compareTo(d2);
		
		log.debug(timei + "|" + timej +"________" + hour + ":" + minute + ":" + secound);

		response.setCharacterEncoding("UTF-8");
		JSONObject resulterror = new JSONObject();
		if(timei != 1 || timej != 1){
			resulterror.put("code", "-1");
			resulterror.put("msg", "非外呼时间段!");		
			return  resulterror;
		}
		//def maplist=eliteBean.chaxun_sql("select count(1) as num from UCIS_OB_end where ob_endtime>='2021-01-01 00:00:00'","dataSource");
		def maplist=eliteBean.chaxun_sql("SELECT (SELECT COUNT(phone1) FROM Ucis_Smssendplan a LEFT JOIN T_IVROBRecord b on a.rec_guid = b.sms_guid LEFT JOIN T_IVROBLog_New c on c.rec_guid = b.rec_guid WHERE a.type_id = 'A00011' and B.status='0' and B.OBResult is null AND b.phone1 is not null AND b.phone1 != '' AND a.OB_STARTTIME is not NULL AND a.OB_STARTTIME < GETDATE() AND a.OB_ENDTIME is not NULL  AND a.OB_ENDTIME > GETDATE() AND a.CTEATEDDATE > DATEADD(MM,DATEDIFF(MM,0,GETDATE()),0) AND a.CTEATEDDATE < DATEADD(MS,-3,DATEADD(MM, DATEDIFF(m,0,GETDATE())+1, 0)) and c.rec_guid is null  ) + (SELECT COUNT(phone1) FROM Ucis_Smssendplan a LEFT JOIN T_IVROBRecord_AAA b on a.rec_guid = b.sms_guid LEFT JOIN T_IVROBLog_New c on c.rec_guid = b.rec_guid WHERE a.type_id = 'A00012' and B.status='0' and B.OBResult is null AND b.phone1 is not null AND b.phone1 != '' AND a.OB_STARTTIME is not NULL AND a.OB_STARTTIME < GETDATE() AND a.OB_ENDTIME is not NULL  AND a.OB_ENDTIME > GETDATE() AND a.CTEATEDDATE > DATEADD(MM,DATEDIFF(MM,0,GETDATE()),0) AND a.CTEATEDDATE < DATEADD(MS,-3,DATEADD(MM, DATEDIFF(m,0,GETDATE())+1, 0)) and c.rec_guid is null  ) num","dataSource");
		def map=maplist[0];
		int num=map.get("num");	

		def phoneno,typeid;

		if(num==0){
			resulterror.put("code", "-1");
			resulterror.put("msg", "未找到外呼数据！");		
			return  resulterror;
		}
		try{
			//获取电话号码
			def ivrobs = eliteBean.chaxun_sql("SELECT PARAMETERVALUE FROM SYSC_PARAMETER WHERE PARAMETER_ID = 'IVROBS'","dataSource");
			def topsum = ivrobs[0].get("PARAMETERVALUE");
			def maplist2=eliteBean.chaxun_sql("SELECT  top "+topsum+"  phone1,a.type_id,b.sms_guid,b.rec_guid FROM Ucis_Smssendplan a LEFT JOIN T_IVROBRecord b on a.rec_guid = b.sms_guid LEFT JOIN T_IVROBLog_New c on c.rec_guid = b.rec_guid  WHERE a.type_id = 'A00011' and B.status='0' and B.OBResult IS NULL AND b.phone1 is not null AND b.phone1 != '' AND a.OB_STARTTIME is not NULL AND a.OB_STARTTIME < GETDATE() AND a.OB_ENDTIME is not NULL AND a.OB_ENDTIME > GETDATE() AND a.CTEATEDDATE > DATEADD(MM,DATEDIFF(MM,0,GETDATE()),0) AND a.CTEATEDDATE < DATEADD(MS,-3,DATEADD(MM, DATEDIFF(m,0,GETDATE())+1, 0)) and c.rec_guid is null  UNION all SELECT  top "+topsum+"  phone1,a.type_id,b.sms_guid,b.rec_guid FROM Ucis_Smssendplan a LEFT JOIN T_IVROBRecord_AAA b on a.rec_guid = b.sms_guid LEFT JOIN T_IVROBLog_New c on c.rec_guid = b.rec_guid  WHERE a.type_id = 'A00012' and B.status='0' and B.OBResult IS NULL AND b.phone1 is not null AND a.OB_STARTTIME is not NULL AND a.OB_STARTTIME < GETDATE() AND a.OB_ENDTIME is not NULL AND a.OB_ENDTIME > GETDATE() AND b.phone1 != '' AND a.CTEATEDDATE > DATEADD(MM,DATEDIFF(MM,0,GETDATE()),0) AND a.CTEATEDDATE < DATEADD(MS,-3,DATEADD(MM, DATEDIFF(m,0,GETDATE())+1, 0)) and c.rec_guid is null ","dataSource");
			def ivrsum = maplist2.size();//本次总数
			def ivrcou = 0;//记录本次外呼有效号码总数
			if(maplist2.size()>0){
				def IVRlist;
				String jsonone = "";
				String Sms_guid = "";
				String Type_id = "";

				for(int i=0;i<maplist2.size();i++){
					
					//log.debug("maplist2[i]:"+maplist2[i]);
					
					def curmap=maplist2[i];
					typeid=curmap.get("type_id");
					phoneno=curmap.get("phone1");
					def rejson=seleteUser(phoneno);
					//log.debug("rejson:"+rejson);
					if(rejson.code==1){

						String Rec_guid = curmap.get("rec_guid");
						String Tel = phoneno;
						String Address = rejson.addrs;
						String AllMoney = rejson.piace;
						Sms_guid = curmap.get("sms_guid");
						Type_id = typeid;

						String text = "";
						if(Address == "") {
							text = "深圳水务集团催交通知：您已拖欠费用" + AllMoney + "元，如逾期交费需按日计收滞纳金。请您及时交费。详情可回拨此号码咨询。";
						}else {
							text = "深圳水务集团催交通知：您用水地址" + Address + "，已拖欠费用" + AllMoney + "元，如逾期交费需按日计收滞纳金。请您及时交费。详情可回拨此号码咨询。";
						}
						//写入数据库记录
						def updateIVROBLog = "INSERT INTO T_IVROBLog_New (Rec_guid,Tel,Address,AllMoney,Sms_guid,obtext,Creatdate,type) VALUES ('" + Rec_guid + "','" + Tel + "','" + Address + "','" + AllMoney + "','" + Sms_guid + "','" + text + "',GETDATE(),'"+typeid+"')";
						eliteBean.update(updateIVROBLog, "dataSource");
						//更新催缴表
						if(Type_id == "A00011"){
							def updateRecord = "update T_IVROBRecord set status = 1 where Sms_guid = '" + Sms_guid + "' and Rec_guid = '" + Rec_guid + "'";
							eliteBean.update(updateRecord, "dataSource");
						}else if(Type_id == "A00012"){
							def updateRecord_AAA = "update T_IVROBRecord_AAA set status = 1 where Sms_guid = '" + Sms_guid + "' and Rec_guid = '" + Rec_guid + "'";			
							eliteBean.update(updateRecord_AAA, "dataSource");
						}

						if(ivrcou>0){
							jsonone = jsonone + ",";
						}
						jsonone = jsonone + "{\"telephone\":\"" + Tel + "\",\"text\":\"" + text + "\"}";
						ivrcou = ivrcou + 1;						  
					}else if(typeid=="A00012"){
						if(rejson.code==2){
							IVRlist = "update T_IVROBRecord_AAA set OBResult='5000',DTMF='5',Status='5',StringField9 = '当月已交清' where rec_guid='"+curmap.get("rec_guid")+"'";
							eliteBean.update(IVRlist,"dataSource");
							//log.debug(IVRlist);
						}else if(rejson.code == -9999){
							IVRlist = "update T_IVROBRecord_AAA set OBResult='5000',DTMF='5',Status='5',StringField9 = '查询不到用户信息！' where rec_guid='"+curmap.get("rec_guid")+"'";
							eliteBean.update(IVRlist,"dataSource");
							//log.debug(IVRlist);
						}
					}else if(typeid=="A00011" ){
						if(rejson.code==2){
							IVRlist = "update T_IVROBRecord set OBResult='5000',DTMF='5',Status='5',StringField9 = '当月已交清' where rec_guid='"+curmap.get("rec_guid")+"'";
							eliteBean.update(IVRlist,"dataSource");
							//log.debug(IVRlist);
						}else if(rejson.code == -9999){
							IVRlist = "update T_IVROBRecord set OBResult='5000',DTMF='5',Status='5',StringField9 = '查询不到用户信息！' where rec_guid='"+curmap.get("rec_guid")+"'";
							eliteBean.update(IVRlist,"dataSource");
							//log.debug(IVRlist);
						}
					}
				}
				/* //屏蔽时间校验
				timei = 1;
				timej = 1; */
				if(timei == 1 && timej == 1){
					log.debug("批次信息Sms_guid:"+Sms_guid);
					IVRlist=IVROB(Sms_guid,eliteBean,Type_id,jsonone);
				}
				log.debug(jsonone);
				return IVRlist;
			}
		}catch(Exception e){
			resulterror.put("code", "-1");
			resulterror.put("msg", "接口异常！"+e);
			return  resulterror;
		}
	}
	//查询用户相关信息
	public static JSONObject seleteUser(String phoneno){

			String charset = "utf-8";
			int timeout = 120000;
			def xmlbody = """<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
								<SOAP-ENV:Body>
									<m:GetUsers xmlns:m="http://tempuri.org/">
									<m:userCode></m:userCode>
									<m:userName></m:userName>
									<m:telePhone>"""+phoneno+"""</m:telePhone>			
									<m:waterUseAddress></m:waterUseAddress>
									<m:bankAccountCode></m:bankAccountCode>
									<m:reportDeptID></m:reportDeptID>
									</m:GetUsers>
								</SOAP-ENV:Body>
							</SOAP-ENV:Envelope>""";
			//log.debug("用户信息接口:"+xmlbody);
			//调用部门信息接口
			def url='http://138.0.0.96:7799/WaterMeterService.asmx';

			Map headMap=new HashMap(); //设置头文件
			headMap.put("Content-Type","text/xml");
			def xml=Util.doHttpPostUseHead(url,xmlbody,charset,timeout,0,headMap);
			//log.debug("用户信息接口结果-111--"+xml);			
			xml = Util.Transform(xml); //去命令空间
			xml = new XmlParser().parseText(xml); //xml解析
			//log.debug("用户信息接口结果---"+xml);
			def result ="";
			try{
				result = xml.Body.GetUsersResponse.GetUsersResult.CallCenterUser;
			}catch (Exception e){
				result="";
				log.error("EM1:",e);
			};
			/*log.debug("----result---："+result);
			log.debug("size"+result.size());
			if(result==null||(result!=null&&result.size()==0)){
				return "{\"code\":\"-1\",\"msg\":\"调用接口返回异常，请查看日志\"}";
			}*/
			
			def piace =0;
			def addrs;
			//ThisPayAmount 本期未交、HistoryPayAmount-历史拖欠、ShouldPayLateFee-滞纳金
			result.each{
			try{
				if(it.ThisPayAmount.text()!='0' || it.HistoryPayAmount.text()!='0' || it.ShouldPayLateFee.text()!='0'){
					piace=piace+Float.parseFloat(it.ThisPayAmount.text())+Float.parseFloat(it.HistoryPayAmount.text())+Float.parseFloat(it.ShouldPayLateFee.text());
				}

				//log.debug("缴费---"+piace);
				addrs=it.WaterUseAddress.text();
			}catch (Exception e){
				log.error("EM2:",e);
			};
			};
			JSONObject resulterror = new JSONObject();			
			String num=piace;
			def code=1;

			if(piace>0){
				String str=num.substring(num.indexOf(".")+1,num.length());
				if(str.length()<2){
					num=num.substring(0,num.indexOf(".")+str.length()+1);
				}else{
					num=num.substring(0,num.indexOf(".")+3);
				}
			}

			//用于测试去除调度接口返回结果
			/* resulterror.put("code", 1);
			resulterror.put("piace", "123.45");
			resulterror.put("addrs", "五和大道");	
			return  resulterror; */
			
			if(num=="0" || num=="0.00"){
				code=2;//未欠费的
			}
			if(result.size()>1){
				resulterror.put("code", code);
				resulterror.put("piace", num);
				resulterror.put("addrs", "");	
				return  resulterror;
			}else if(result.size()==1){
				resulterror.put("code", code);
				resulterror.put("piace", num);
				resulterror.put("addrs", addrs);	
				return  resulterror;
			}else if(result.size()<1){
				resulterror.put("code", -9999);
				resulterror.put("piace", num);
				resulterror.put("addrs", "");	
				return  resulterror;
			}
	}
	//调用容大IVR外呼接口
	public static String IVROB(String Sms_guid,EliteBean eliteBean,String Type_id,String ivrarr) {
		long startTime = System.currentTimeMillis();

		String reJson = null;
		try {
			//生成timestamp
			String IVRtimestamp = eliteBean.chaxun_sql("SELECT CONVERT(varchar(100),GETDATE(),112) + REPLACE(CONVERT(varchar(100),GETDATE(),108), ':', '')","dataSource");
			IVRtimestamp = IVRtimestamp.replace('[','');
			IVRtimestamp = IVRtimestamp.replace(']','');
			IVRtimestamp = IVRtimestamp.replace(':','');
			IVRtimestamp = IVRtimestamp.replace('=','');
			IVRtimestamp = IVRtimestamp.replace('{','');
			IVRtimestamp = IVRtimestamp.replace('}','');
			log.debug("timestapm:"+IVRtimestamp);

			//生成Sign
			//String IVRSign = eliteBean.chaxun_sql("select UPPER(substring(sys.fn_sqlvarbasetostr(HashBytes('MD5','AppId=guohebing&Timestamp=" + IVRtimestamp + "&Token=ghbToken123')),3,32))","dataSource");
			String IVRSign = eliteBean.chaxun_sql("select UPPER(substring(sys.fn_sqlvarbasetostr(HashBytes('MD5','AppId=crm&Timestamp=" + IVRtimestamp + "&Token=crmToken123')),3,32))","dataSource");
			IVRSign = IVRSign.replace('[','');
			IVRSign = IVRSign.replace(']','');
			IVRSign = IVRSign.replace(':','');
			IVRSign = IVRSign.replace('=','');
			IVRSign = IVRSign.replace('{','');
			IVRSign = IVRSign.replace('}','');
			log.debug("Sign:" + IVRSign);

			//固定测试号码
			//Tel = "17704075650";

			//测试
			//String jsonString = "{\"TaskName\":\"CRM-催缴外呼\",\"TextToSpeech\":\"催缴外呼\",\"Priority\":\"2\",\"Type\":\"催缴\",\"AppId\":\"guohebing\",\"Sign\":\""+ IVRSign +"\",\"Timestamp\":\"" + IVRtimestamp + "\",\"Info\":[" + ivrarr +"]}";
			//生产
			String jsonString = "{\"TaskName\":\"CRM-催缴外呼\",\"TextToSpeech\":\"催缴外呼\",\"Priority\":\"2\",\"Type\":\"催缴\",\"AppId\":\"crm\",\"Sign\":\""+ IVRSign +"\",\"Timestamp\":\"" + IVRtimestamp + "\",\"Info\":[" + ivrarr +"]}";

			//json
			JSONObject ivrobj = new JSONObject(jsonString);

			log.debug("原始的json:" + ivrobj);

			//接口
			Map headMap = new HashMap();
			headMap.put("Content-Type","application/json");

			def charset="utf-8";
			def timeout=300000;
			def enablessLfag=0;

			def url = "http://10.200.2.147/RDConnector/OutboundInfo.html";//生产地址
			//def url = "http://10.200.2.151:8001/RDConnector/OutboundInfo.html";//测试地址
			log.debug("url="+url);

			//接口调用
			def jsonBack=Util.doHttpPostUseHead(url,jsonString,charset,timeout,enablessLfag,headMap);
			log.debug("jsonBack1:"+jsonBack);

			JSONObject inJson = new JSONObject(jsonBack);

			String StatusCode = inJson.StatusCode;
			String IVRId = inJson.ID;	
			//更新sign和Timestamp
			def updateIVROBLog = "update T_IVROBLog_New set Timestamp = '"+IVRtimestamp+"',Sign = '"+IVRSign+"',Id = '" + IVRId + "',StatusCode = '" + StatusCode + "' where sms_guid = '" + Sms_guid + "' and Timestamp is null and Sign is null";
			eliteBean.update(updateIVROBLog, "dataSource"); 

			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"提交IVR外呼任务成功，使用时长(毫秒):" + (endTime - startTime) + "\",\"data\":"+jsonBack+"}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"提交IVR外呼任务失败(" + e.getMessage() + "),使用时长(毫秒):" + (endTime - startTime) + "\",\"data\":{}}";
		}

		return reJson;
	}
	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}
}